package com.franklin.ideaplugin.easytesting.javaagent;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.franklin.ideaplugin.easytesting.common.utils.MyPathUtil;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.jar.JarFile;
import java.util.stream.Collectors;

/**
 * @author Ye Junhui
 * @since 2023/7/19
 */
public class AgentUtils {

    private final static String AGENT_SEPARATOR = "!;!";

    public final static String AGENT_OPS_PATH = "agent/ops";

    /**
     * 构建agent参数
     * @param agentPaths
     * @return
     */
    public static String buildAgentOps(String basePath,Collection<String> agentPaths){
        String path = agentPaths.stream()
                .filter(StrUtil::isNotBlank)
                .collect(Collectors.joining(AGENT_SEPARATOR));
        String opsPath = MyPathUtil.getEtServerPath(basePath) + AGENT_OPS_PATH;
        FileUtil.writeString(path,opsPath, StandardCharsets.UTF_8);
        return path;
    }

    /**
     * 读取agent参数
     * @return
     */
    public static String getAgentOps(){
        String cacheBasePath = MyPathUtil.getCacheBasePath(AGENT_OPS_PATH);
        return FileUtil.readString(cacheBasePath,StandardCharsets.UTF_8);
    }

    /**
     * 解析agent参数
     * @param agentOps
     * @return
     */
    public static List<JarFile> resolveAgentOps(String agentOps){
        if (StrUtil.isBlank(agentOps)){
            return Collections.emptyList();
        }
        List<JarFile> jarFileList = Arrays.stream(agentOps.split(AGENT_SEPARATOR))
                .map(agentPath -> {
                    File file = FileUtil.file(agentPath);
                    if (!file.exists()) {
                        return null;
                    }
                    try {
                        return new JarFile(file);
                    } catch (IOException e) {
                        //ignore
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        return jarFileList;
    }
}
